package com.habdqn.easybuy.dao.impl;

import com.habdqn.easybuy.dao.BaseDao;
import com.habdqn.easybuy.dao.ProductCategoryDao;
import com.habdqn.easybuy.entity.ProductCategory;
import com.habdqn.easybuy.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/11/30
 */
public class ProductCategoryDaoImpl extends BaseDao implements ProductCategoryDao {
    private String baseSelect = "SELECT id, name, parent_id FROM product_category";

    @Override
    public ProductCategory queryById(Integer id) {
        String sql = baseSelect + " WHERE id=? ";
        List<ProductCategory> categories = getListByRS(executeQuery(sql,id));
        if (categories!=null && categories.size()>0){
            return categories.get(0);
        }
        return null;
    }

    @Override
    public List<ProductCategory> queryByParentId(int parentId) {
        String sql = baseSelect + " WHERE parent_id=? ";
        return getListByRS(executeQuery(sql,parentId));
    }

    @Override
    public int insert(ProductCategory productCategory) {
        String sql = "INSERT INTO product_category(name, parent_id) VALUES(?,?)";
        return executeInsert(sql,productCategory.getName(),productCategory.getParentId());
    }

    @Override
    public int update(ProductCategory productCategory) {
        String sql = "UPDATE product_category SET name=?, parent_id=? WHERE id=?";
        return executeUpdate(sql,productCategory.getName(),productCategory.getParentId(),productCategory.getId());
    }

    @Override
    public int deleteById(Integer id) {
        String sql = "DELETE FROM product_category WHERE id=?";
        return executeUpdate(sql,id);
    }

    /**
     * 从结果集中提取对象集合
     *
     * @param rs 结果集
     * @return 用户集合
     */
    private List<ProductCategory> getListByRS(ResultSet rs) {
        List<ProductCategory> categories = null;
        try {
            if (rs != null) {
                categories = new ArrayList<>();
                while (rs.next()) {
                    ProductCategory category = new ProductCategory();
                    category.setId(rs.getInt("id"));
                    category.setName(rs.getString("name"));
                    category.setParentId(rs.getInt("parent_id"));
                    categories.add(category);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return categories;
    }
}
